<template>
  <div class="search-container">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon>
      <el-autocomplete
        v-model="searchValue"
        :fetch-suggestions="querySearch"
        placeholder="美图秀秀 🔥"
        class="search-input"
        clearable
        @select="handleSelect"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-autocomplete>
    </div>

    <!-- 搜索记录 -->
    <div class="section">
      <div class="section-header">
        <span class="section-title">搜索记录</span>
        <span class="clear-btn" @click="clearSearchHistory">清空</span>
      </div>
      <div class="tags-container">
        <el-tag v-for="tag in searchHistory" :key="tag" class="history-tag" @click="searchByTag(tag)">
          {{ tag }}
        </el-tag>
      </div>
    </div>

    <!-- 热搜推荐 -->
    <div class="section">
      <div class="section-header">
        <span class="section-title">热搜推荐</span>
        <span class="more-btn" @click="showMore('hotSearch')">
          更多 <el-icon><ArrowRight /></el-icon>
        </span>
      </div>
      <div class="app-list">
        <div v-for="app in hotApps.appList" :key="app.id" class="app-item" @click="toDetial(app.id)">
            <img :src="app.url" :alt="app.name" class="app-icon" />
            <div class="app-name">{{ app.name }}</div>
            <el-button size="small" type="primary" plain class="install-btn">安装</el-button>
        </div>
      </div>
    </div>

    <!-- 发现更多应用 -->
    <div class="section">
      <div class="section-header">
        <span class="section-title">发现更多应用</span>
        <span class="more-btn" @click="showMore('moreApps')">
          更多 <el-icon><ArrowRight /></el-icon>
        </span>
      </div>
      <div class="app-list">
        <div v-for="app in moreApps.appList" :key="app.id" class="app-item" @click="toDetial(app.id)">
            <img :src="app.url" :alt="app.name" class="app-icon" />
            <div class="app-name">{{ app.name }}</div>
            <el-button size="small" type="primary" plain class="install-btn">安装</el-button>
        </div>
      </div>
    </div>

    <!-- 休闲游戏精选 -->
    <!-- <div class="section">
      <div class="section-header">
        <span class="section-title">休闲游戏精选</span>
        <span class="more-btn" @click="showMore('games')">
          更多 <el-icon><ArrowRight /></el-icon>
        </span>
      </div>
      <div class="app-list">
        <div v-for="game in games.appList" :key="game.id" class="app-item">
          <img :src="game.url" :alt="game.name" class="app-icon" />
          <div class="app-name">{{ game.name }}</div>
          <el-button size="small" type="primary" plain class="install-btn">安装</el-button>
        </div>
      </div>
    </div> -->

    <!-- App使用次数榜 -->
    <!-- <div class="section">
      <div class="section-header">
        <span class="section-title">
         <img src="@/assets/gold.svg" style="width: 30px; height: 30px; margin-right: 5px;"> App使用次数榜
        </span>
        <span class="more-btn" @click="showMore('ranking')">
          更多 <el-icon><ArrowRight /></el-icon>
        </span>
      </div>
      <div class="ranking-list">
        <div v-for="(app, index) in rankingApps.appList" :key="app.id" class="ranking-item">
          <span class="rank-number" :class="{ 'top-rank': index < 3 }">{{ index + 1 }}</span>
          <img :src="app.url" :alt="app.name" class="app-icon" />
          <div class="app-info">
            <div class="app-name" style="text-align: left;font-size: 14px;font-weight: bold;">{{ app.name }}</div>
            <div class="app-detail">
              <span>{{ app.location }}</span>
            </div>
          </div>
          <el-button size="small" type="primary" plain class="install-btn">安装</el-button>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
import {
  ref,
  getCurrentInstance,
  onMounted
} from 'vue';

const global = getCurrentInstance()?.appContext.config.globalProperties;

onMounted(() => {
  global?.$http.get('/AppStore/toSearch')
    .then((resp: any) => {
      hotApps.value = resp.data.hot;
      console.log(hotApps.value);
      moreApps.value = resp.data.more;
      games.value = resp.data.game;
      rankingApps.value = resp.data.rank;
    })

    global?.$http.get('/AppStore/list')
    .then((resp: any) => {
      appList.value = resp.data;
    })
})

const router = useRouter();
const searchValue = ref('');
const searchHistory = ref(['拼多多']);

const hotApps = ref({tagName: 'hot', appList: []});

const moreApps = ref({tagName: 'more', appList: []});

const games = ref({tagName: 'game', appList: []});

const rankingApps = ref({tagName: 'rank', appList: []});
const appList = ref([]);

const goBack = () => {
  router.back();
};

const handleSearch = () => {
  if (searchValue.value.trim()) {
    if (!searchHistory.value.includes(searchValue.value)) {
      searchHistory.value.unshift(searchValue.value);
    }
    console.log('搜索:', searchValue.value);
  }
};

const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? appList.value.filter((app: any) => {
        return app.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0;
      })
    : [];
  cb(results.map((app: any) => ({
    value: app.name,
    id: app.id,
    icon: app.url
  })));
};

const handleSelect = (item: any) => {
  searchValue.value = item.value;
  if (item.id) {
    toDetial(item.id);
  }
};

const searchByTag = (tag: string) => {
  searchValue.value = tag;
  handleSearch();
};

const clearSearchHistory = () => {
  searchHistory.value = [];
};

const showMore = (section: string) => {
  if(section=='hotSearch'){
    router.push({path:"/RankingList",query:{userId:1}})
  }else{
    router.push({path:"/AppList",query:{userId:1}})
  }
};

const toDetial = (id: any) => {
  router.push({path:"/AppView/"+id,query:{userId:1}})
};


</script>

<style scoped>
.search-container {
  padding: 10px 15px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-icon {
  font-size: 24px;
  margin-right: 10px;
  cursor: pointer;
}

.search-input {
  flex: 1;
}

.section {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 10px;
  padding: 15px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.clear-btn, .more-btn {
  color: #409EFF;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.history-tag {
  cursor: pointer;
}

.app-list {
  display: flex;
  overflow-x: auto;
  gap: 15px;
  padding: 5px 0;
}

.app-list::-webkit-scrollbar {
  display: none;
}

.app-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 80px;
  max-width: 80px;
}

.app-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  object-fit: cover;
}

.app-name {
  margin: 8px 0;
  font-size: 12px;
  text-align: center;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.install-btn {
  padding: 2px 10px;
  font-size: 12px;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.ranking-item {
  display: flex;
  align-items: center;
}

.rank-number {
  width: 20px;
  text-align: center;
  font-weight: bold;
  margin-right: 10px;
}

.top-rank {
  color: #f56c6c;
}

.app-info {
  flex: 1;
  margin-left: 10px;
  position: relative;
}

.app-detail {
  font-size: 12px;
  color: #909399;
  display: flex;
  gap: 10px;
}

.app-tag {
  position: absolute;
  bottom: 0;
  right: 0;
  color: #e6a23c;
  font-size: 12px;
}
</style>